package top.kaoshanji.p1ch03a;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import top.kaoshanji.u1constant.FileConstant;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * 代码清单 p1ch03a-08：对文件通道的绝对位置进行读写操作的示例
 * author kaoshanji
 * ^_^
 * create time 2025/1/6 19:00
 */
public class FileChannelExample02 {

    private static final Logger logger = LogManager.getLogger(FileChannelExample02.class);

    public static void main(String[] args) throws IOException {
        logger.info("...代码清单 p1ch03a-08：对文件通道的绝对位置进行读写操作的示例...");

        FileChannel channel = FileChannel.open(Paths.get(FileConstant.LOCAL_ROOT_PATH.concat("p1ch03a08.txt")),
                StandardOpenOption.READ, StandardOpenOption.CREATE, StandardOpenOption.WRITE);

        ByteBuffer writeBuffer = ByteBuffer.allocate(4).putChar('A').putChar('B');
        writeBuffer.flip();

        channel.write(writeBuffer, 1024);

        ByteBuffer readBuffer = ByteBuffer.allocate(2);
        channel.read(readBuffer, 1026);

        readBuffer.flip();

        System.out.println(readBuffer.getChar());

    }

}
